package com.coolw.dynamic.thread.pool.context;

import com.coolw.dynamic.thread.pool.entity.ThreadPoolConfigEntity;
import com.coolw.dynamic.thread.pool.service.ThreadPoolConfigService;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.collection.CollUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 线程池初始化创建器
 *
 * @author coolw
 * @date 2024/5/21 19:34
 */
@Component
public class ThreadPoolInitCreator implements InitializingBean, DisposableBean {

    @Autowired
    private ThreadPoolConfigService configService;

    @Override
    public void afterPropertiesSet() throws Exception {
        createThreadPool();
    }

    @Override
    public void destroy() throws Exception {
        closeThreadPool();
    }

    private void createThreadPool() {
        List<ThreadPoolConfigEntity> configList = configService.list();
        if (CollUtil.isEmpty(configList)) {
            return;
        }

        List<ThreadPoolProperties> properties = BeanUtil.copyToList(configList, ThreadPoolProperties.class);

        // 创建线程池
        DynamicThreadPoolManager.getInstance().createThreadPool(properties);
    }

    public void closeThreadPool() {
        // 关闭线程池
        DynamicThreadPoolManager.getInstance().closeThreadPool();
    }
}
